<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="数据字典管理">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
        :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :bordered="false" :pagination="false">
        <template #tableTitle>
          <n-space>
            <n-button type="primary" :on-click="handleEdit.bind(null, {}, 1)">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              添加字典
            </n-button>
            <n-button type="primary" :loading="btnLoading" :on-click="refreshCache">
              <template #icon>
                <n-icon>
                  <SyncOutlined />
                </n-icon>
              </template>
              刷新缓存
            </n-button>
          </n-space>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle" style="border-radius: 8px;">
      <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
        <n-form-item label="字典分组" path="dictGroup">
          <n-input maxlength="32" show-count :disabled="inputDisabled" placeholder="请输入字典分组"
            v-model:value="fromValues.dictGroup" />
        </n-form-item>
        <n-form-item label="字典KEY" path="dictKey">
          <n-input maxlength="32" show-count placeholder="请输入字典KEY" v-model:value="fromValues.dictKey" />
        </n-form-item>
        <n-form-item label="字典名称" path="dictName">
          <n-input maxlength="100" show-count placeholder="请输入字典名称" v-model:value="fromValues.dictName" />
        </n-form-item>
        <n-form-item label="字典值" path="dictValue">
          <n-input maxlength="100" show-count placeholder="请输入字典值" v-model:value="fromValues.dictValue" />
        </n-form-item>
        <n-form-item label="字典说明" path="dictDesc">
          <n-input maxlength="300" show-count type="textarea" :autosize="{
            minRows: 3,
            maxRows: 5
          }" v-model:value="fromValues.dictDesc" filterable placeholder="请输入字典说明" />
        </n-form-item>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseModel">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, h, reactive } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import { columns } from './columns';
import { dictTreeList, saveDict, updateDict, removeDict, overload } from '@/api/system/dict';
import { DeleteOutlined, EditOutlined, PlusOutlined, SyncOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
const message = useMessage();
const dialog = useDialog();
const formBtnLoading = ref(false);
const actionRef = ref();
const editTitle = ref('');
const isAdd = ref(1);
const showModal = ref(false);
const formRef: any = ref(null);
const inputDisabled = ref(false);
const btnLoading = ref(false);
let fromValues = reactive({
  id: null,
  /** 父级ID */
  parentId: 0,
  /** 字典分组 */
  dictGroup: '',
  /** 字典KEY */
  dictKey: '',
  /** 字典名称 */
  dictName: '',
  /** 字典值 */
  dictValue: '',
  /** 字典说明 */
  dictDesc: '',
});
const rules: FormRules = {
  dictGroup: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入字典分组',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  dictKey: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入字典KEY',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  dictName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入字典名称',
  },
  dictValue: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入字典值',
  },
};
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  {
    field: 'dictName',
    component: 'NInput',
    label: '字典名称',
    componentProps: {
      placeholder: '请输入字典名称',
    },
  },
  {
    field: 'dictGroup',
    component: 'NInput',
    label: '分组标识',
    componentProps: {
      placeholder: '请输入分组标识',
    },
  },
];
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});
const loadDataTable = async (res: any) => {
  return await dictTreeList({ ...getFieldsValue(), ...res });
};
const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
    });
  },
});

function createActions(record) {
  return [
    {
      label: '新增',
      type: 'success',
      icon: PlusOutlined,
      onClick: handleEdit.bind(null, record, 3),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record, 2),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '删除',
      type: 'error',
      // 配置 color 会覆盖 type
      color: 'red',
      icon: DeleteOutlined,
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      //auth: ['basic_list'],
    },
  ];
}
function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}
/**
 * 查询
 */
function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
/**
 * 新增，编辑，新增子节点
 * @param record 
 * @param addStatus 
 */
function handleEdit(record: Recordable, addStatus: number) {
  showModal.value = true;
  isAdd.value = addStatus;
  resetFrom();
  if (addStatus === 1) {
    editTitle.value = `新增网关配置`;
    inputDisabled.value = false;
  }
  if (addStatus === 2) {
    editTitle.value = `编辑 ${record.dictName}`;
    inputDisabled.value = true;
    fromValues = Object.assign(fromValues, record);
  }
  if (addStatus === 3) {
    editTitle.value = `新增 ${record.dictName}子节点`;
    inputDisabled.value = true;
    fromValues = Object.assign(fromValues, { parentId: record.id }, { dictGroup: record.dictGroup });
  }
}
function resetFrom() {
  fromValues = Object.assign(fromValues, {
    id: null,
    /** 父级ID */
    parentId: 0,
    /** 字典分组 */
    dictGroup: '',
    /** 字典KEY */
    dictKey: '',
    /** 字典名称 */
    dictName: '',
    /** 字典值 */
    dictValue: '',
    /** 字典说明 */
    dictDesc: '',
  });
}
/**
 * 新增编辑提交数据
 * @param e 
 */
function confirmForm(e: any) {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      let data: any;
      if (isAdd.value === 2) {
        data = await updateDict(fromValues);
      } else {
        data = await saveDict(fromValues);
      }
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
        formBtnLoading.value = false;
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showModal.value = false;
        resetFrom();
        reloadTable();
      }
      formBtnLoading.value = false;
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
  resetFrom();
  showModal.value = false;
}
/**
 * 删除确认
 * @param record 
 */
function handleDelete(record: Recordable) {
  dialog.warning({
    title: '警告',
    content: `确定删除${record.dictName}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await removeDict({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showModal.value = false;
        reloadTable();
      }
    },
  })
}
function refreshCache() {
  btnLoading.value = true;
  setTimeout(async () => {
    const data = await overload();
    if (data.code !== ResultEnum.SUCCESS) {
      const resultMsg = data.data ? data.data : '';
      message.error(data.mesg + '-' + resultMsg);
      btnLoading.value = false;
    }
    if (data.code === ResultEnum.SUCCESS) {
      message.success(data.mesg);
      btnLoading.value = false;
    }
  }, 500);
}
</script>

<style lang="less" scoped></style>
